import http.client
import json

import mitmproxy
import mitmproxy.http
from mitmproxy import ctx, addons,http


class mockrewrite:
    def response(self, flow: mitmproxy.http.HTTPFlow):
        url = "https://stock.xueqiu.com/v5/stock/batch/quote.json?_t"
        if url in flow.request.pretty_url and "x=" in flow.request.pretty_url:
            ctx.log.info(f"{flow.response.text}")
            ctx.log.info(str(type(flow.response.text)))
            #讲json文件转为字典格式
            data = json.loads(flow.response.text)
            #修改股票名称
            data["data"]["items"][0]["quote"]["name"] ="yaoyao测试"
            data["data"]["items"][1]["quote"]["name"] ="yaoyao测试2"
            data["data"]["items"][2]["quote"]["name"] ="yaoyao测试3"


            #修改股票价格
            data["data"]["items"][0]["quote"]["current"] = "88"
            data["data"]["items"][1]["quote"]["current"] = "88"
            data["data"]["items"][2]["quote"]["current"] = "88"
            #替换响应体
            flow.response.text = json.dumps(data)
            # flow.reponse.text=json.dump(data)

class mockrequest:

    def request(self, flow: mitmproxy.http.HTTPFlow):
        url = "https://stock.xueqiu.com/v5/stock/batch/quote.json?_t"
        if url in flow.request.pretty_url and "x=" in flow.request.pretty_url:
            with open("quote.json",encoding="utf-8") as f:
                flow.response = http.HTTPResponse.make(
                    200,
                    f.read(),

                )



addons = [
    # mockrewrite()
    mockrequest()

]

if __name__=='__main__':
    from mitmproxy.tools.main import mitmdump
    mitmdump(['-p','8080','-s',__file__])
